#include "SList02.h"

SLNode* CreatNode(SDatatype x)
{
	SLNode* newnode = (SLNode*)malloc(sizeof(SLNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}

	newnode->data = x;
	newnode->next = NULL;

	return newnode;
}

void SLprint(SLNode* phead)
{
	SLNode* cur = phead;

	while (cur)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}

	printf("NULL\n");
}

void SLpushfront(SLNode** phead, SDatatype x)
{
	assert(phead);

	if (*phead == NULL)
	{
		SLNode* newnode = (SLNode*)malloc(sizeof(SLNode));
		if (newnode == NULL)
		{
			perror("malloc fail");
			return;
		}
		
		(*phead) = newnode;
		(*phead)->data = x;
		(*phead)->next = NULL;
		return;
	}

	SLNode* newnode = (SLNode*)malloc(sizeof(SLNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;

	newnode->next = *phead;
	*phead = newnode;
}


void SLpushback(SLNode** phead, SDatatype x)
{
	assert(phead);

	SLNode* newnode = CreatNode(x);


	if (*phead == NULL)
	{
		*phead = newnode;
		return;
	}
	else
	{
		SLNode* tail = *phead;

		while (tail->next)
		{
			tail = tail->next;
		}

		tail->next = newnode;
	}
}

void SLpopfront(SLNode** phead)
{
	assert(phead && (*phead));

	SLNode* tmp = *phead;
	*phead = (*phead)->next;

	free(tmp);
	tmp = NULL;
}

void SLpopback(SLNode** phead)
{
	assert(phead && (*phead));

	SLNode* tail = *phead;
	SLNode* prev = *phead;

	while (tail->next)
	{
		prev = tail;
		tail = tail->next;
	}

	prev->next = NULL;

	free(tail);
	tail = NULL;

}

SLNode* SLfind(SListNode* phead, SDatatype x)
{
	//assert(phead);

	SLNode* cur = phead;

	while (cur)
	{
		if (cur->data == x)
			return cur;

		cur = cur->next;
	}

	return NULL;
}

void SLinsertBefor(SLNode** phead, SLNode* pos, SDatatype x)
{
	assert(phead && pos);

	if (*phead == pos)
	{
		SLpushfront(phead, x);
	}
	else
	{
		SLNode* prev = *phead;

		while (prev->next != pos)
		{
			prev = prev->next;
		}

		SLNode* newnode = CreatNode(x);
		prev->next = newnode;
		newnode->next = pos;
	}
}
void SLinsertAfter(SLNode** phead, SLNode* pos, SDatatype x)
{
	assert(phead&&pos);
	
	SLNode* newnode = CreatNode(x);

	SLNode* tmp = pos->next;
	pos->next = newnode;
	newnode->next = tmp;

}

void SLerase(SLNode** phead, SLNode* pos)
{
	assert(phead && (*phead));

	if (*phead = pos)
	{
		free(pos);
		pos = NULL;
	}
	else
	{
		SLNode* prev = *phead;

		while (prev->next != pos)
		{
			prev = prev->next;
		}

		prev->next = pos->next;
		free(pos);
		pos = NULL;
	}
}

void SLeraseAfter(SLNode* pos)
{
	assert(pos);
	assert(pos->next);

	SLNode* tmp = pos->next;
	pos->next = pos->next->next;

	free(tmp);
	tmp = NULL;

}
